<template>
  <BaseContainer>
    <QueryFilter
      :model="queryFields"
      :label-col="{ style: { width: '70px' } }"
      @submit="handleQueryData"
      @reset="resetQueryData"
    >
      <a-form-item name="name" label="词库名称">
        <a-input placeholder="请输入词库名称" v-model:value.trim="queryFields.name" allow-clear />
      </a-form-item>
      <a-form-item name="matchStyle" label="匹配方式">
        <a-select placeholder="请选择匹配方式" v-model:value="queryFields.matchStyle" :options="matchPattern" />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="词库列表">
      <a-button type="primary" @click="handleCreate">
        <template #icon><plus-outlined /></template>
        新建词库
      </a-button>
    </table-toolbar>
    <a-table
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 1000 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'createTime'">
          {{ formatDate(record.createTime) }}
        </template>
        <template v-if="column.key === 'bzLine'">
          {{ BlKeyMap[record.bzLine] }}
        </template>
        <template v-if="column.key === 'matchStyle'">
          {{ PatternKeyMap[record.matchStyle] }}
        </template>
        <template v-if="column.key === 'operate'">
          <a-button type="primary" @click="handleEdit(record)">编辑</a-button>
          <a-popconfirm title="确定要删除吗？" @confirm="handleRemove(record)">
            <a-button class="delete-color ml-2" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <business-line-updater
      v-model:data="formFields"
      v-model:show="dialog.show"
      :mode="dialog.mode"
      :submitting="submitting"
      @on-submit="handleSubmit"
    />
  </BaseContainer>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import getWordLib, { type WordLib } from '@/services/word-lib/getWordLib'
import { formatDate, toLabelValue } from '@/utils'
import updateWordLib from '@/services/word-lib/updateWordLib'
import removeWordLib from '@/services/word-lib/removeWordLib'
import BusinessLineUpdater from './components/BusinessLineUpdater.vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import BaseContainer from '@/components/base-container/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import Divider from '@/components/divider/index.vue'
import { PatternEnum, PatternKeyMap } from '@/views/word-lib/interface'
import { Mode } from '@/core/interfaces/common'
import { BlKeyMap } from '@/core/mapper/platform'

const defaultQueryFields = () => ({
  name: '',
  matchStyle: PatternEnum.ALL
})

const defaultFormFields = () => ({
  id: undefined,
  name: '',
  matchStyle: undefined
})

const queryFields = reactive(defaultQueryFields())
const formFields = ref(defaultFormFields())

const dialog = reactive({
  mode: Mode.create,
  show: false
})

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

const matchPattern = ref(toLabelValue(PatternKeyMap))

const columns = [
  {
    title: '词库名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '匹配方式',
    dataIndex: 'matchStyle',
    key: 'matchStyle'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    key: 'creator'
  },
  {
    title: '操作',
    dataIndex: 'operate',
    key: 'operate',
    width: '170px'
  }
]

const tableData = ref<WordLib[]>([])
const [, queryTableData, loading] = getWordLib()
const [, submitWordLib, submitting] = updateWordLib()
const [, deleteWordLib] = removeWordLib()

async function loadBusinessLine() {
  const [err, res] = await queryTableData({
    ...queryFields,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
    tableData.value = res.data.data.wordLibs
  }
}

async function handleSubmit() {
  const [err] = await submitWordLib(formFields.value, dialog.mode)

  if (!err) {
    dialog.show = false
    await handleQueryData()
  }
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadBusinessLine()
}

function handleQueryData() {
  pagination.pageSize = 15
  pagination.current = 1
  loadBusinessLine()
}

function resetQueryData() {
  Object.assign(queryFields, defaultQueryFields())
  pagination.pageSize = 15
  pagination.current = 1
  loadBusinessLine()
}

function handleCreate() {
  dialog.show = true
  dialog.mode = Mode.create
  formFields.value = defaultFormFields()
}

function handleEdit(record: WordLib) {
  dialog.show = true
  dialog.mode = Mode.edit
  formFields.value = Object.assign(defaultFormFields(), record)
}

async function handleRemove(record: WordLib) {
  const [err, res] = await deleteWordLib({
    id: record.id
  })

  if (!err) {
    message.success(res.data.msg || '删除成功')
    await loadBusinessLine()
  } else {
    message.error(err.message || '删除失败，请稍候再试...')
  }
}

onMounted(() => {
  loadBusinessLine()
})
</script>

<script lang="ts">
export default {
  name: 'WordLibrary'
}
</script>
